package com.laowang.blog.service;

import com.laowang.blog.mapper.BUserMapper;
import com.laowang.blog.model.BUser;
import com.laowang.blog.model.BUserExample;
import com.laowang.blog.model.User;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Service
public class BUserService implements UserDetailsService {
    @Autowired
    private BUserMapper bUserMapper;

    public BUser findUserByName(String username){
        BUserExample example = new BUserExample();
        example.createCriteria()
                .andUsernameEqualTo(username);
        return bUserMapper.selectByExample(example).get(0);
    }


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        return this.findUserByName(username);
    }

    public Collection<? extends GrantedAuthority> getAuthorities(int userId) {
        BUser user = bUserMapper.selectByPrimaryKey(userId);

        List<GrantedAuthority> list = new ArrayList<>();
        list.add(new GrantedAuthority() {

            @Override
            public String getAuthority() {
                switch (user.getType()) {
                    case 1:
                        return "AUTHORITY_ADMIN";
                    case 2:
                        return "AUTHORITY_MODERATOR";
                    default:
                        return "AUTHORITY_USER";
                }
            }
        });
        return list;
    }
}
